<template>
  <a-drawer
      :title="title"
      :width="$store.getters.isMobile ? 350 : 460"
      :visible="visible"
      :body-style="{
        height: canApproval?'calc(100% - 120px )':'100%',
        boxSizing: 'border-box',
        overflowY: 'auto',
      }"
      @close="onClose"
      :destroyOnClose="true"
  >
    <!-- 线索信息 -->
    <div class="content-box">
      <a-form :model="formsPut" ref="formRef" layout="vertical">
        <template v-for="field in templateFields" :key="field.alias">
          <a-col :span="24" v-if="field.alias=='contact_name'">
            <a-form-item label="客户名称" name="contact_name">
              {{ detail.contact_name }}
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="field.alias=='contact_phone'">
            <a-form-item label="客户手机号" name="contact_phone">
              <span>{{ detail.contact_phone }}</span>
              <div
                  v-if="detail.format_type  == 2&&!detail.full_phone"
                  style="
                color: #2681f3;
                margin-left: 3px;
                display: inline;
                cursor: pointer;
              "
                  @click="fullPhone"
              >
                补全
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="field.alias=='company'">
            <a-form-item label="公司">
              <div>{{ detail.company || "--" }}</div>
            </a-form-item>
          </a-col>
          <template v-if="field.alias=='village_id'">
            <a-col :span="24">
              <a-form-item label="意向项目">
                <div>{{ detail.village_name || "--" }}</div>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="楼宇名称">
                <div>{{ detail.build_name || "--" }}</div>
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="24" v-if="field.alias=='expect_area'">
            <a-form-item label="需求面积段">
              <a-input-group size="default">
                <span>{{ detail.expect_area_min }}</span>
                -
                <span>{{ detail.expect_area_max }}</span>
                ㎡
              </a-input-group>
            </a-form-item>
          </a-col>

          <a-col :span="24" v-if="field.alias=='remark'">
            <a-form-item label="备注">
              <div>{{ detail.remark || "--" }}</div>
            </a-form-item>
          </a-col>
        </template>


        <a-col :span="24">
          <a-form-item label="渠道名称">
            <div>{{ detail.channel_name || "--" }}</div>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="所属渠道公司">
            <div>{{ detail.channel_company_name || "--" }}</div>
          </a-form-item>
        </a-col>

        <div class="title" v-if="detail.diy_field&&detail.diy_field.length>0">附加字段</div>
        <a-col :span="24" v-if="detail.diy_field&&detail.diy_field.length>0">
          <template v-for="field in detail.diy_field">
            <div class="m-t-20"
                 v-if="field.type=='input'||field.type=='textarea'||field.type=='singleSelect'">
              <span>{{ field.name }}：</span>
              <span>{{ field.content }}</span>
            </div>
            <div class="m-t-20"
                 v-else-if="field.type=='mutiSelect'">
              <span>{{ field.name }}：</span>
              <template v-for="(contentItem,index) in field.content">
                <span v-if="index!=0">,</span>
                <span>{{ contentItem }}</span>
              </template>
            </div>
            <div class="m-t-20"
                 v-else-if="field.type=='image'">
              <span>{{ field.name }}：</span>
              <a-space>
                <a-image v-for="src in field.content" :src="src.url" :width="50"/>
              </a-space>

            </div>
            <div class="m-t-20 flex flex-start"
                 v-else-if="field.type=='file'">
              <div>{{ field.name }}：</div>
              <div class="flex-1">
                <template v-for="(src,index) in field.content">
                  <div class="text-blue" style="cursor: pointer"
                       @click.stop="downloadFile(src.url)">{{ index + 1 }}.{{ src.name }}
                  </div>
                </template>
              </div>
            </div>
          </template>
        </a-col>


      </a-form>
    </div>

    <a-row style="padding-left: 10px;">
      <a-col :span="24" v-if="remarksList.length">
        <div class="title" style="font-weight: 600">跟进历史</div>
        <a-timeline style="margin-top: 15px">
          <a-timeline-item v-for="(item, index) in remarksList">
            <p>
              {{ item.created_at }}
            </p>
            <p v-if="item?.operate_content?.status_txt">
              状态：{{ item.operate_content.status_txt || "--" }}
            </p>
            <p v-if="item?.operate_content?.remark">
              内容：{{ item.operate_content.remark || "--" }}
            </p>
            <p
                v-if="
                    item?.operate_content?.user_name ||
                    item?.operate_content?.user_phone
                  "
            >
              跟进人： {{ item?.operate_content?.user_name }}
              {{ item?.operate_content?.user_phone }}
            </p>
          </a-timeline-item>
        </a-timeline>
      </a-col>
      <a-col :span="24" v-if="detail?.changeRecord?.length">
        <div class="title" style="font-weight: 600">线索所属渠道变更历史</div>
        <a-timeline style="margin-top: 20px">
          <a-timeline-item v-for="(item, index) in detail?.changeRecord">
            <p>
              {{ item.created_at }}
            </p>
            <p v-if="item?.remark">
              内容：{{ item.remark || "--" }}
            </p>

          </a-timeline-item>
        </a-timeline>
      </a-col>
    </a-row>

    <a-modal
        :visible="editPhoneVisible"
        title="补全手机号码"
        @cancel="editPhoneVisible = false"
        @ok="commitEditPhone"
    >
      <a-form layout="vertical" ref="phoneForm" :model="phoneModel">
        <a-form-item label="客户">
          <span>{{ detail?.contact_name || '--' }}</span>
        </a-form-item>
        <a-form-item label="客户手机号" :rules="[{required:true,message:'请输入客户手机号'}]"
                     name="phone">
          <a-input type="tel" v-model:value="phoneModel.phone"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>


    <div class="drawer-footer" v-if="canApproval">
      <a-space>
        <a-button type="primary" @click="changeApprovalStatus(1)">同意</a-button>
        <a-button type="primary" danger @click="changeApprovalStatus(0)">拒绝</a-button>
      </a-space>
    </div>


    <a-modal v-model:visible="rejectVisible" title="拒绝" @ok="handleReject">
      <a-form>
        <a-form-item label="拒绝原因" name="reject_reason" v-bind="validateInfos.reject_reason">
          <a-textarea placeholder="请输入拒绝原因" v-model:value="modelRef.reject_reason"/>
        </a-form-item>
      </a-form>
    </a-modal>


  </a-drawer>
</template>

<script>
import {watch, ref, reactive, toRefs, createVNode} from "vue";
import request from "../../../../common/utils/request";
import {Form, message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from '@ant-design/icons-vue'

const useForm = Form.useForm

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    canApproval: {
      type: Boolean,
      default: false,
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      title: "线索详情",
      detail: {},
      list: [],
      itemList: [],
      editPhoneVisible: false,
      templateFields: [],
      rejectVisible: false,


    });


    const formRef = ref();
    const followForm = reactive({
      status: "",
      status_content: "", //跟进内容
      values: "",
      operation_uid: undefined,
      next_time: "",
    });

    // let ids = 0;
    // let name = "";
    // let phone = "";
    const handleReset = (clearFilters, confirm) => {
      clearFilters();
      page.value = 1;
      confirm();
    };
    const activeKey = ref("1")

    // 跟进
    const remarksList = ref([]);
    const getRemarkList = () => {
      request
          .get("/org", "/business/clue/clueFollowRecord", {id: props.id})
          .then((res) => {
            console.log(res.list);
            remarksList.value = res.list;
          });
    };

    const getDetail = () => {
      const id = props.id;
      request
          .get("/org", "/business/clue/detail", {
            id,
          })
          .then((res) => {
            state.detail = res.detail;
            console.log(state.detail);
          });
    };

    const modelRef = reactive({
      reject_reason: ""
    })
    const ruleRef = reactive({
      reject_reason: [{
        required: true,
        message: "请输入拒绝原因",
      }],
    })
    const {validate, resetFields, validateInfos} = useForm(modelRef, ruleRef)

    const getDefaultField = () => {
      const params = {
        is_root: 1,
      }
      request.get("/org", "/business/clueField/getClueDiyField", params).then(res => {
        state.templateFields = res.data
      })

    }

    const formsPut = reactive({
      contact_name: "",
      contact_phone: "",
      company: "",
      building: "",
      expect_area_min: "",
      expect_area_max: "",
      area: "",
      // channel_id: "",
      remark: "",
    });

    const setModelRef = (state) => {
      for (let key in state) {
        formsPut[key] = state[key];
      }
    };

    const operation_name = ref("");
    const handleOperation = (value, change) => {
      operation_name.value = change.label;
    };

    const onClose = () => {
      context.emit("closeDetail");
    };

    const fullPhone = () => {
      state.editPhoneVisible = true;
    };

    const phoneForm = ref()
    const phoneModel = reactive({
      phone: ""
    })
    const commitEditPhone = () => {
      console.log(phoneForm.value)
      phoneForm.value.validateFields().then(() => {
        const param = {
          phone: phoneModel.phone,
          id: props.id
        }
        console.log(param)
        request.post("/org", "/user/clue/fullPhone", param).then(res => {
          console.log(res)
          message.success("操作成功")
          state.editPhoneVisible = false;
          context.emit("back");
        })

      })
    }

    //线索状态
    const optionsStatus = ref([]);
    const getStatusList = () => {
      request.get("/org", "/business/clueStatus/clueStatusList").then((res) => {
        console.log(res);
        const temList = res.list.map((item) => {
          return {
            label: item.name,
            value: item.status,
          };
        });
        optionsStatus.value = temList;
      });
    };


    const handleReject = () => {

      validate().then(() => {
        request.post("/org", "/business/customer/channel/handleClue", {
          id: props.id,
          status: 3,
          reject_reason: modelRef.reject_reason
        }).then(res => {
          console.log(res)
          state.rejectVisible = false
          message.success("操作成功!")
          context.emit("closeDetail");
        })
      })

    }

    const handleAgree = () => {
      request.post("/org", "/business/customer/channel/handleClue", {
        id: props.id,
        status: 2,
      }).then(res => {
        console.log(res)
        message.success("操作成功!")
        resetFields()
        context.emit("closeDetail");
      })
    }

    const changeApprovalStatus = (val) => {
      if (val == 1) {
        //同意
        Modal.confirm({
          title: () => "提示",
          content: () => "确定通过该申请吗？",
          icon: () => createVNode(ExclamationCircleOutlined),
          okText: () => "确定",
          onOk() {
            handleAgree()
          },
        });
      } else {
        // 拒绝
        state.rejectVisible = true
      }
    }


    const init = () => {
      setTimeout(() => {
        console.log(props.id)
      }, 2000)
      getDetail();
      getRemarkList();
      getStatusList();
      getDefaultField()
      // contentList();
    };

    watch(
        () => props.visible,
        (val) => {
          console.log("1111111111111")
          if (val) {

            init();
          }
        }
    );


    const downloadFile = (src) => {
      window.open(src);
    };

    return {
      followForm,
      ...toRefs(state),
      formsPut,
      onClose,
      activeKey,
      optionsStatus,
      formRef,
      remarksList,
      fullPhone,
      commitEditPhone,
      phoneModel,
      phoneForm,
      downloadFile,
      handleReject,
      handleAgree,
      changeApprovalStatus,
      validateInfos,
      modelRef
    };
  },
};
</script>

<style lang="less" scoped>
.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.radio-box {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  text-align: center;
  padding: 0 16px;
}

.content-box {
  flex: 1;
  padding: 10px;
  overflow: auto;
}

:deep(.ant-image) {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  overflow: hidden;
}

.title {
  height: 30px;
  line-height: 30px;
  color: #333;
  font-weight: 500;
  font-size: 15px;
  position: relative;
  padding-left: 10px;
}

.title::before {
  content: "";
  position: absolute;
  left: 0px;
  top: 8px;
  width: 4px;
  height: 14px;
  background-color: #1c90ff;
  border-radius: 4px;
}

.m-t-20 {
  margin-top: 20px;
}

:deep(.ant-timeline-item) {
  padding-bottom: 10px;
}
</style>
